package com.xywy.start;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.MLog;
import com.xywy.common.util.StringUtils;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.me.SetupAcValMobileActivity;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

/**
 * 会员登陆
 * 
 * @author xiaogd
 * 
 */
public class LoginActivity extends BaseActivity {
	private EditText account;
	private EditText pwd;
	private ImageView mCancel;
	private ImageView pCancel;
	private Context mContext;
	private Button button;
	private TextView tvGo;
	private TextView tvBack;
	private int from;
	private int sex;
	private int height;
	private String birthday;
	private TextView name;
	private String mobile;
	private TextView password;
	private String account1;
	private String password1;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.start_login);

		this.preInit();
		this.initView();
		this.loadData();
		this.setListener();
	}

	/**
	 * 进行验证,发送网络请求
	 */
	private void btnLogin() {
		boolean flag = false;
		if (account.getText().toString() == null
				|| account.getText().toString().length() == 0) {
			Toast.makeText(mContext, getString(R.string.me_account_not_null),
					Toast.LENGTH_LONG).show();
			flag = true;
			return;
		} else if (pwd.getText().toString() == null
				|| pwd.getText().toString().length() == 0) {
			Toast.makeText(mContext, getString(R.string.me_pwd_not_null),
					Toast.LENGTH_LONG).show();
			flag = true;
			return;
		}
		if (!flag) { // 提交数据
			this.sendMsg();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	public void preInit() {
		mContext = this.context;
//		from = this.getIntent().getIntExtra("from", 0);
//		sex = this.getIntent().getIntExtra("sex", 0);
//		height = this.getIntent().getIntExtra("height", 0);
//		account1 = this.getIntent().getStringExtra("account");
//		mobile = this.getIntent().getStringExtra("mobile");
//		password1 = this.getIntent().getStringExtra("password");

		// backIntetent.putExtra("sex", sex);
		// backIntetent.putExtra("height", height);
		// backIntetent.putExtra("birthday", birthday);
		// // 名字
		// backIntetent.putExtra("account", name.getText().toString());
		// // 手机号
		// backIntetent.putExtra("mobile", mobile.getText().toString());
		// // 密码
		// backIntetent.putExtra("password", password.getText().toString());

	}

	@Override
	public void loadData() {

	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.start_login_title_bar);
		TextView tvTitle = titleBar.getTitle();
		tvGo = titleBar.getGo();
		tvGo.setVisibility(View.GONE);
		tvBack = titleBar.getTvBack();
		tvBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				back();

			}
		});

		// titleBar.onClickBack(this);
		tvTitle.setText(getString(R.string.et_start_login));
		// tvGo.setText(getString(R.string.tv_start_login_switch));
		mCancel = (ImageView) findViewById(R.id.iv_start_login_mcancel);
		pCancel = (ImageView) findViewById(R.id.iv_start_login_pcancel);

		account = (EditText) findViewById(R.id.et_login_account);
		pwd = (EditText) findViewById(R.id.et_login_pwd);

		button = (Button) findViewById(R.id.bt_start_login);
//		SharedPreferences sp = context.getSharedPreferences("config",
//				Context.MODE_PRIVATE);
//		String mobile = sp.getString("mobile", "");
//		String pwdStr = sp.getString("password", "");
//		account.setText(mobile);
//		pwd.setText(pwdStr);
		List<User> users = UserKeeper.getLastLoginUser(this);
		if(users != null && users.size()>0){
			account.setText(users.get(0).getPhonenum());
		}else {
			account.setText("");
		}
		// tvGo.setOnClickListener(new View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent(LoginActivity.this,
		// LoginSwitch1Activity.class);
		// startActivity(intent);
		// }
		// });
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			back();
			return true;
		}
		return false;
	}

	private void back() {
		// TODO Auto-generated method stub
		// if (from == 1) {
		// Intent backIntetent = new Intent(mContext, RegisterActivity.class);
		// backIntetent.putExtra("from", 1);
		// backIntetent.putExtra("sex", sex);
		// backIntetent.putExtra("height", height);
		// backIntetent.putExtra("birthday", birthday);
		// // 名字
		// backIntetent.putExtra("account", account1);
		// // 手机号
		// backIntetent.putExtra("mobile", mobile);
		// // 密码
		// backIntetent.putExtra("password", password1);
		// startActivity(backIntetent);
		// this.finish();
		// } else {
		Intent backIntent = new Intent(mContext, MainActivity.class);
		backIntent.putExtra("source", 1);
		startActivity(backIntent);
		LoginActivity.this.finish();
		// }
	}

	MyProgress myProgress;
	JSONObject msgBack = null;
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			if (null != msg.obj) {
				try {
					msgBack = new JSONObject(msg.obj.toString());
				} catch (JSONException e) {
					e.printStackTrace();
					myProgress.stop();
				}
				if (msgBack.optInt("state") == ResultCode.SUCCESS) {
//					int height = msgBack.optInt("height");
//					MLog.i(TAG, "当前账户的height" + height);
//					String userid = msgBack.optString("userid");
//					int isregister = msgBack.optInt("isregister");
					// int age = msgBack.optInt("");

					User user = saveUser(msg.obj.toString());
					MLog.i(TAG, "当前人的userid:" + user.getUserid() + "当前人的isregister："
							+ user.getIsregister());
					if(user == null ){
						Toast.makeText(mContext, "服务器返回信息有误",
								Toast.LENGTH_LONG).show();
						myProgress.stop();
						return ;
					}
					
					UserKeeper.saveUser(user, mContext);
//					UserKeeper.getUserAvatar(mContext, user, AvatarHandler);
					
					if (Integer.parseInt(user.getHeight()) == 0) {

//						UserKeeper.saveUser(user, mContext);
						Intent intent = new Intent(mContext,
								HeightActivity.class);
						intent.putExtra("userid", user.getUserid());
						mContext.startActivity(intent);
					} else if (Integer.parseInt(user.getIsregister()) == 0) {
//						UserKeeper.saveUser(user, mContext);
						Intent intent = new Intent(mContext,
								SetupAcValMobileActivity.class);
						intent.putExtra("userid", user.getUserid());
						mContext.startActivity(intent);
					} else {
						UserKeeper.getUserAvatar(mContext, user, AvatarHandler);
						// 将 userid 存入本地
//						SharedPreferences sp = context.getSharedPreferences(
//								"config", Context.MODE_PRIVATE);
//						SharedPreferences.Editor editor = sp.edit();
//						editor.putString("userid", userid);
//						Log.i(TAG + ">>>>>>>>>>>>>>>>>", userid);
//						editor.putString("mobile", account.getText().toString());
//						editor.putInt("height", height);
//						editor.putString("password", pwd.getText().toString());
//						editor.commit();
//						UserKeeper.saveUser(user, mContext);
//						
//						Intent intent = new Intent(mContext,
//								FragmentMainActivity.class);
//						mContext.startActivity(intent);
//						finish();
					}

				} else {
					myProgress.stop();
					Toast.makeText(mContext, msgBack.optString("error"),
							Toast.LENGTH_LONG).show();
					return;
				}
			}else {
				myProgress.stop();
			}
		}
	};
	
	Handler AvatarHandler = new Handler(){
		public void handleMessage(Message msg) {
			myProgress.stop();
			switch (msg.what) {
			case ResultCode.NULL:
				Toast.makeText(LoginActivity.this, "服务器返回异常", Toast.LENGTH_SHORT).show();
				break;
			case ResultCode.FAIL:
				Toast.makeText(LoginActivity.this, "网络异常,请稍后重试", Toast.LENGTH_SHORT).show();
				break;
			case ResultCode.SUCCESS:
				Intent intent = new Intent(mContext,
						FragmentMainActivity.class);
				mContext.startActivity(intent);
				break;

			default:
				break;
			}
		};
	};

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;

	// 处理网络请求
	public void sendMsg() {
		myProgress = new MyProgress(this, 10);
		
		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 请求路径
		paramsParser.action = getString(R.string.login_bypwd);
		// 请求方式
		paramsParser.request = "post";

		// 请求参数
		params.put("phonenum", account.getText().toString());
		params.put("password", pwd.getText().toString());

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.context;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}
		
//		public <T extends Parser> void onNoNetWork(T paramParser, int resultCode) {
//			 runOnUiThread(new Runnable() {
//				public void run() {
//					myProgress.stop();
//					Toast.makeText(LoginActivity.this, "暂无网络连接", Toast.LENGTH_SHORT).show();
//				}
//			});
//		};
	};

	private void setListener() {
		account.addTextChangedListener(mTextWatcher);
		pwd.addTextChangedListener(pTextWatcher);
	}

	boolean mFlag = false;

	TextWatcher mTextWatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence charSequence, int i, int i2,
				int i3) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void afterTextChanged(Editable editable) {
			if (editable.length() > 0) {
				mCancel.setVisibility(View.VISIBLE);
				mFlag = true;
				if (nFlag) {

				}
			} else {
				mCancel.setVisibility(View.INVISIBLE);
				mFlag = false;
				// button.setBackgroundDrawable(mContext.getResources()
				// .getDrawable(R.drawable.shape_button_bgwhite));
				// button.setClickable(false);
			}
			if (!StringUtils.isNull(account.getText().toString())
					&& !StringUtils.isNull(pwd.getText().toString())) {
				button.setBackgroundDrawable(mContext.getResources()
						.getDrawable(R.drawable.shape_button));
				button.setClickable(true);
			} else {
				button.setBackgroundDrawable(mContext.getResources()
						.getDrawable(R.drawable.shape_button_bgwhite));
				button.setClickable(false);
			}
		}
	};

	boolean nFlag = false;
	TextWatcher pTextWatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence charSequence, int i, int i2,
				int i3) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void afterTextChanged(Editable editable) {
			if (editable.length() > 0) {
				pCancel.setVisibility(View.VISIBLE);
				nFlag = true;
				if (mFlag) {
					// button.setBackgroundDrawable(mContext.getResources()
					// .getDrawable(R.drawable.shape_button));
					// button.setClickable(true);
				}
			} else {
				pCancel.setVisibility(View.INVISIBLE);
				nFlag = false;
				// button.setBackgroundDrawable(mContext.getResources()
				// .getDrawable(R.drawable.shape_button_bgwhite));
				// button.setClickable(false);
			}
			if (!StringUtils.isNull(account.getText().toString())
					&& !StringUtils.isNull(pwd.getText().toString())) {
				button.setBackgroundDrawable(mContext.getResources()
						.getDrawable(R.drawable.shape_button));
				button.setClickable(true);
			} else {
				button.setBackgroundDrawable(mContext.getResources()
						.getDrawable(R.drawable.shape_button_bgwhite));
				button.setClickable(false);
			}
		}
	};

	public void loginOnClick(View view) {
		switch (view.getId()) {
		case R.id.iv_start_login_mcancel:
			account.setText("");
			break;
		case R.id.iv_start_login_pcancel:
			pwd.setText("");
			break;
		case R.id.bt_start_login:
			btnLogin();
			// Intent intent1 = new Intent(mContext,
			// FragmentMainActivity.class);
			// mContext.startActivity(intent1);
			break;
		case R.id.tv_login_for_pwd:
			Intent intent = new Intent(mContext, ForgetPwdActivity.class);
			startActivity(intent);
			break;
		case R.id.tv_valcode_login: // 用验证码登陆
			Intent intent2 = new Intent(mContext, LoginValCodeActivity.class);
			startActivity(intent2);
			break;
		}
	}
	
	private User saveUser(String str){
		User user = new User();
		try {
			JSONObject json = new JSONObject(str);
			user.setUserid(json.optString("userid"));
			user.setIsregister(json.optString("isregister"));
			user.setPhonenum(json.optString("phonenum"));
			user.setHeight(json.optString("height"));
			user.setBirthday(json.optString("birthday"));
			user.setSex(json.optString("sex"));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return user;
	}
}
